#    Copyright 2012 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

import sys
NeededPaths=['/opt/coopip/djangoproject/include', '/opt/coopip/djangoproject', '/opt/cis', '/opt/oms/', '/opt/amr', '/opt/gis','/opt/gos', '/opt']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
import httplib
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings, datetime
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib.gis import admin
import _mysql as mysql
from django.db import transaction
import django, urllib
import COOPIP_Form
import CIS, AMR, GIS, GOS  #Comment this out before doing a syncdb
from ftplib import FTP
import django.db
import ipbase
import datetime



class Substation(models.Model):
    using='default'
    AMRsubid=models.IntegerField(unique=True, db_column='amrsubrid')
    AMRSubstationStatus=models.IntegerField(null=True, blank=True, db_column='amrsubstationstatus')
    Name=models.TextField(unique=True, db_column='name')
    AMRCommandsOut=models.IntegerField(db_column='amrcommandsout')
    AMRSearchesOut=models.IntegerField(db_column='amrsearchesout')
    LastUpdateDateTime=models.DateTimeField(db_column='lastupdatedatetime')
    #AMRSearchesOut=AMR.Outcmd.objects.filter(subid=substation.AMRsubid).filter(funccode=300).count()  #Alternative way of calculating searches out
    objects=models.GeoManager()
    class Meta:
        db_table=u'substation'
        app_label='djangoproject'
    def __unicode__(self):
        return self.Name
    @staticmethod
    def RefreshCache():
        Scemain=AMR.Scemain.objects.all()
        for scemain in Scemain:
            Substations = Substation.objects.filter(AMRsubid = scemain.subid)
            if(not Substations):
                New=Substation()
                New.AMRsubid = scemain.subid
                New.Name = scemain.subname
                New.AMRSubstationStatus = scemain.substatus
                subcmdqstatus=AMR.Subcmdqstatus.objects.filter(subid=Substations[0].AMRsubid)[0]
                New.AMRCommandsOut=AMR.Outcmd.objects.exclude(funccode=300).filter(subid=New.AMRsubid).count()
                New.AMRSearchesOut=AMR.Outcmd.objects.filter(funccode=300).filter(subid=New.AMRsubid).count()
                New.LastUpdateDateTime=datetime.datetime.now()
                New.save()
            else:
                Existing=Substations[0]
                Existing.Name = scemain.subname
                Existing.AMRSubstationStatus = scemain.substatus
                Existing.AMRCommandsOut=AMR.Outcmd.objects.exclude(funccode=300).filter(subid=Existing.AMRsubid).count()
                Existing.AMRSearchesOut=AMR.Outcmd.objects.filter(funccode=300).filter(subid=Existing.AMRsubid).count()
                Existing.LastUpdateDateTime=datetime.datetime.now()
                Existing.save()







class AMRSerialNumber(models.Model):
    """AMRSerialNumber caches the AMR SerialNumber table locally to reduce the number of slow connections necessary to the AMR Server"""
    using='default'
    serialnumber=models.IntegerField(null=True, blank=True, db_column='serialnumber')
    utilacctid=models.IntegerField(null=True, blank=True, db_column='utilacctid')
    premiseid=models.TextField(null=True, blank=True, db_column='premiseid')
    subid=models.IntegerField(null=True, blank=True, db_column='subid')
    busid = models.IntegerField(null=True, blank=True, db_column='busid')
    fdrid = models.IntegerField(null=True, blank=True, db_column='fdrid')
    phase = models.IntegerField(null=True, blank=True, db_column='phase')
    signal = models.IntegerField(null=True, blank=True, db_column='signal')
    detection = models.IntegerField(null=True, blank=True, db_column='detection')
    type = models.IntegerField(null=True, blank=True, db_column='type')
    model = models.IntegerField(null=True, blank=True, db_column='model')
    protectivedevice = models.TextField(null=True, blank=True, db_column='protectivedevice')
    transformergrid = models.TextField(null=True, blank=True, db_column='transformergrid')
    installdate = models.DateTimeField(null=True, blank=True, db_column='installdate')
    districtnumber = models.IntegerField(null=True, blank=True, db_column='districtnumber')
    deviceloc = models.TextField(null=True, blank=True, db_column='deviceloc')
    activeflag = models.TextField(null=True, blank=True, db_column='activeflag')
    oneway = models.TextField(null=True, blank=True, db_column='oneway')
    lastgoodcommdt = models.DateTimeField(null=True, blank=True, db_column='lastgoodcommdt')
    lasttrycommdt = models.DateTimeField(null=True, blank=True, db_column='lasttrycommdt')
    bytecount = models.IntegerField(null=True, blank=True, db_column='bytecount')
    usedbytecount = models.IntegerField(null=True, blank=True, db_column='usedbytecount')
    totcommfailcnt = models.IntegerField(null=True, blank=True, db_column='totcommfailcnt')
    conseccommfailcnt = models.IntegerField(null=True, blank=True, db_column='conseccommfailcnt')
    commtype = models.TextField(null=True, blank=True, db_column='commtype')
    devicetype = models.IntegerField(null=True, blank=True, db_column='devicetype')
    connecttype = models.TextField(null=True, blank=True, db_column='connecttype')
    connectdate = models.DateTimeField(null=True, blank=True, db_column='connectdate')
    user1 = models.TextField(null=True, blank=True, db_column='user1')
    user2 = models.TextField(null=True, blank=True, db_column='user2')
    metertype = models.TextField(null=True, blank=True, db_column='metertype') #Metertype from meteraccts
    meterrateclass = models.TextField(null=True, blank=True, db_column='meterrateclass') #meterrateclass from meteraccts
    metercyclenumber = models.TextField(null=True, blank=True, db_column='metercyclenumber') #metercyclenumber from meteraccts
    meterclass = models.TextField(null=True, blank=True, db_column='meterclass') #meterclass from meteraccts
    hourlyconvhmultiplier=models.FloatField(null=True, blank=True, db_column='hourlyconvhmultiplier') #From Hourlyconv [based on metertype]
    hourlyconvhdivisor=models.FloatField(null=True, blank=True, db_column='hourlyconvhdivisor') #From Hourlyconv [based on metertype]
    feedername=models.TextField(null=True, blank=True, db_column='feedername') #feedername from feeder
    substationname=models.TextField(null=True, blank=True, db_column='substationname') #subname from scemain
    class Meta:
        db_table='amrserialnumber'
        app_label='djangoproject'
    @staticmethod
    def RefreshCache():
        UpdatedCache=list(AMR.Serialnumber.objects.all())
        AMRMeterTypeDict={}
        AMRMeterRateClassDict={}
        AMRMeterCycleNumberDict={}
        AMRMeterClassDict={}
        Meteraccts=list(AMR.Meteraccts.objects.all())
        for i in Meteraccts:
            AMRMeterTypeDict[i.serialnumber]=i.metertype
            AMRMeterRateClassDict[i.serialnumber]=i.meterrateclass
            AMRMeterCycleNumberDict[i.serialnumber]=i.metercyclenumber
            AMRMeterClassDict[i.serialnumber]=i.meterclass

        AMRHourlyConvDict={}
        HourlyconvList=list(AMR.Hourlyconv.objects.all())
        for i in HourlyconvList:
           AMRHourlyConvDict[i.metertype]=[i.hmultiplier, i.hdivisor]
        #Missing AMRHourlyConversions:
        AMRHourlyConvDict['S415K'] = [0.036, 1]  #Estimate based on a reading, was missing from the Hourlyconv table, AMR uses other unknown tables for this value
        AMRHourlyConvDict['AL0.6'] = [0.180722892, 1]
        AMrHourlyConvDict['UMT_2.10'] = [1, 1] #UMT_2.10 meters do not seem to have hourly interval readings
        AMrHourlyConvDict['UMT_4.10'] = [1, 1] #UMT_4.10 meters do not seem to have hourly interval readings


        if(len(UpdatedCache) < 10000):
            return  #Reality Check on the number of records returned from the AMR Database
        AMRSerialNumber.objects.all().delete()
        for i in UpdatedCache:
            New=AMRSerialNumber()
            New.serialnumber=i.serialnumber
            New.utilacctid=i.utilacctid
            New.premiseid=i.premiseid
            New.subid=i.subid
            New.busid=i.busid
            New.fdrid=i.fdrid
            New.phase=i.phase
            New.signal=i.signal
            New.detection=i.detection
            New.type=i.type
            New.model=i.model
            New.protectivedevice=i.protectivedevice
            New.transformergrid=i.transformergrid
            New.installdate=i.installdate
            New.districtnumber=i.districtnumber
            New.deviceloc=i.deviceloc
            New.activeflag=i.activeflag
            New.oneway=i.oneway
            New.lastgoodcommdt=i.lastgoodcommdt
            New.lasttrycommdt=i.lasttrycommdt
            New.bytecount=i.bytecount
            New.usedbytecount=i.usedbytecount
            New.totcommfailcnt=i.totcommfailcnt
            New.conseccommfailcnt=i.conseccommfailcnt
            New.commtype=i.commtype
            New.devicetype=i.devicetype
            New.connecttype=i.connecttype
            New.connectdate=i.connectdate
            New.user1=i.user1
            New.user2=i.user2
            try:
                New.metertype=AMRMeterTypeDict[New.serialnumber]
                New.meterrateclass = AMRMeterRateClassDict[New.serialnumber]
                if(not New.meterrateclass):
                    New.meterrateclass='UNKNOWN'
                New.metercyclenumber=AMRMeterCycleNumberDict[New.serialnumber]
                if(not New.metercyclenumber):
                    New.metercyclenumber='UNKNOWN'
                New.meterclass=AMRMeterClassDict[New.serialnumber]
                if(not New.meterclass):
                    New.meterclass='UNKNOWN'

            except KeyError:
                New.metertype='UNKNOWN'
                New.meterrateclass='UNKNOWN'
                New.metercyclenumber='UNKNOWN'
                New.meterclass='UNKNOWN'
            try:
                New.hourlyconvhmultiplier=AMRHourlyConvDict[New.metertype][0]
                New.hourlyconvhdivisor=AMRHourlyConvDict[New.metertype][1]
            except KeyError:
                print "Missing hourlyconv key:  " + str(New.metertype)
                New.hourlyconvhmultiplier=None
                New.hourlyconvhdivisor=None
            try:
                feeder=AMR.Feeder.objects.filter(subid=i.subid).filter(busid=i.busid).filter(fdrid=i.fdrid)[0]
                New.feedername=feeder.feedername
            except:
                New.feedername='UNKNOWN'
            try:
                scemain=AMR.Scemain.objects.filter(subid=i.subid)[0]
                New.substationname=scemain.subname
            except:
                New.substationname='UNKNOWN'
            New.save()


class MeterModel(models.Model):
    """List of Meter Models with Conversion Factors for Pulse to KWH"""
    using='default'
    Name=models.TextField(db_column='name', unique=True)
    PulseToKWHMultiplier=models.FloatField()
    PulseToKWHDivisor=models.FloatField()
    #MeterConvKH=models.FloatField(null=True, blank=True, db_column='meterconvkh')
    meterconvmit=models.FloatField(null=True, blank=True, db_column='meterconvmit')  #Not sure what this column is intended for, using as a divisor for demand calculations
    HourlyReadingIndicator=models.NullBooleanField(db_column='hourlyreadingindicator', null=True, blank=True)
    objects=models.GeoManager()
    class Meta:
        db_table=u'metermodel'
        app_label='djangoproject'
    def __unicode__(self):
        return str(self.id)
    def RefreshCache(self):
        """Add and Update all Meter Models from AMR"""
        Meterconv=AMR.Meterconv.objects.all()
        if(not MeterModel.objects.filter(Name='UNKNOWN')):
            New=MeterModel()
            New.Name='UNKNOWN'
            New.PulseToKWHMultiplier=1
            New.PulseToKWHDivisor=1
            New.meterconvkh=1
            New.meterconvmit=1
            New.meterconvdivisor=1
            New.save()
        for meterconv in Meterconv:
            meterModel=MeterModel.objects.filter(Name=meterconv.metertype)
            if(not meterModel):
                meterModel=MeterModel()
                meterModel.Name=meterconv.metertype
            else:
                meterModel=meterModel[0]
            meterModel.PulseToKWHMultiplier=float(meterconv.meterconvkh)
            meterModel.PulseToKWHDivisor=float(meterconv.meterconvdivisor)
            meterModel.meterconvmit=float(meterconv.meterconvmit)
            meterModel.save()

class CountOfPingResponse(models.Model):
    using='default'
    Count=models.IntegerField(db_column='count')
    DateTime=models.DateTimeField(db_column='datetime')
    objects=models.GeoManager()
    class Meta:
        db_table='countofpingresponse'
        app_label='djangoproject'
    def RefreshCache(self):
        New=CountOfPingResponse()
        New.DateTime=datetime.datetime.now()
        New.Count=AMR.Tctpingresplog.objects.all().count()
        New.save()

class MeterBlinkImportFile(models.Model):
    using='default'
    FileName=models.TextField(db_column='filename', db_index=True, unique=True)
    RawData=models.TextField(db_column='rawdata', null=True, blank=True)
    ImportDateTime=models.DateTimeField(db_column='datetime', null=True, blank=True)
    FileDateTime=models.DateTimeField(db_column='filedatetime', null=True, blank=True)
    FileParsedIndicator=models.NullBooleanField(db_column='fileparsedindicator', null=True, blank=True)
    objects=models.GeoManager()
    class Meta:
        db_table=u'meterblinkimportfile'
        app_label='djangoproject'
    def ImportFiles(self):
        Path = '/mnt/amr/users/TCEC/AMR'
        PotentialFiles=os.listdir(Path)
        OutageFiles=[]   #MeterBlink Files are called Outage Files, example filename:  OUTAGE_COUNT_28SEP2011.DAT
        for i in PotentialFiles:
            if(i[:7] == "OUTAGE_" and ".DAT" in i):
                OutageFiles.append(i)
        total = len(OutageFiles)
        Count = 0
        Temp = 0
        for filename in OutageFiles:
            Count = Count + 1
            print "On:  " + str(Count) + ' of ' + str(total)
            if(MeterBlinkImportFile.objects.filter(FileName=filename).count()):
                continue
            print "Starting:  " + str(filename)
            print datetime.datetime.now()
            OutageFile=open(Path + '/' + filename)
            NewFile=MeterBlinkImportFile()
            NewFile.FileName=filename
            try:
                Day=filename[13:15]
                Year=filename[18:22]
                Month=self.MonthNameToNumber(filename[15:18])
                NewFile.FileDateTime=datetime.datetime(year=int(Year), month=int(Month), day=int(Day))
            except IOError:
                print "Could not parse date for:  " + str(filename)
                continue
            NewFile.ImportDateTime=datetime.datetime.now()
            NewFile.RawData=OutageFile.read()
            OutageFile.close()
            NewFile.save()
    def MonthNameToNumber(self, Name):
        if(Name == 'JAN'):
            return 1
        elif(Name == 'FEB'):
            return 2
        elif(Name == 'MAR'):
            return 3
        elif(Name == 'APR'):
            return 4
        elif(Name == 'MAY'):
            return 5
        elif(Name == 'JUN'):
            return 6
        elif(Name == 'JUL'):
            return 7
        elif(Name == 'AUG'):
            return 8
        elif(Name == 'SEP'):
            return 9
        elif(Name == 'OCT'):
            return 10
        elif(Name == 'NOV'):
            return 11
        elif(Name == 'DEC'):
            return 12
        else:
            raise Exception('MonthNametoNumber Had an Invalid Month Name:  ' + str(Name))

class AMRSearchLogFile(models.Model):
    using='default'
    SerialNumber=models.IntegerField(db_column='serialnumber', null=True, blank=True)
    ParseDateTime=models.DateTimeField(db_column='parsedatetime', null=True, blank=True)
    CompleteDateTime=models.DateTimeField(db_column='completedatetime',  null=True, blank=True)
    AddIndicator=models.NullBooleanField(db_column='addindicator', null=True, blank=True)  #This search Added a new meter
    ModIndicator=models.NullBooleanField(db_column='modindicator', null=True, blank=True)  #This search modified an existing meter
    MeterNotFoundIndicator=models.NullBooleanField(db_column='meternotfoundindicator', null=True, blank=True)  #This search was not successful
    RawData=models.TextField(db_column='rawdata',  null=True, blank=True)
    objects=models.GeoManager()
    class Meta:
        db_table=u'amrsearchlogfile'
        app_label='djangoproject'
    def ImportDataFromLogFile(self):
        ftp=FTP(djangoproject.settings.AMRIPAddress)
        ftp.login(djangoproject.settings.AMRLogFileUserName, djangoproject.settings.AMRLogFilePassword)
        FileList=[]
        ftp.retrlines('NLST', FileList.append)
        if djangoproject.settings.AMRLogFileName in FileList:
            LogLines=[]
            ftp.retrlines('RETR ' + djangoproject.settings.AMRLogFileName, LogLines.append)
            for line in LogLines:
                if len(line) < 6:
                    continue
                new=AMRSearchLogFile()
                new.RawData=line
                new.save()
            try:
               ftp.delete(djangoproject.settings.AMRLogFileName)
            except:
               pass
        ftp.close()
        self.ParseLogFile()
    def ParseLogFile(self):
        AMRSearchLogFiles=AMRSearchLogFile.objects.filter(ParseDateTime__isnull=True).order_by('id')
        for i in AMRSearchLogFiles:
            print 'In ParseLogFile:  ' + i.RawData
            if i.RawData[:3] == 'MOD':
                if 'successful' in i.RawData or ' De-assign failed' in i.RawData:
                    i.AddIndicator=False
                    i.ModIndicator=True
                    i.MeterNotFoundIndicator=False
                else:
                    i.AddIndicator=False
                    i.ModIndicator=False
                    i.MeterNotFoundIndicator=True
            elif i.RawData[:3] == 'ADD':
                if 'successful' in i.RawData:
                    i.AddIndicator=False
                    i.ModIndicator=True
                    i.MeterNotFoundIndicator=False
                elif 'Add to SN' in i.RawData:
                    i.AddIndicator=True
                    i.ModIndicator=False
                    i.MeterNotFoundIndicator=False
                else:
                    i.AddIndicator=False
                    i.ModIndicator=False
                    i.MeterNotFoundIndicator=True
            else:
                i.ParseDateTime=datetime.datetime.now()
                i.save()
                continue
            i.CompleteDateTime=datetime.datetime.strptime(i.RawData[-20:], '%d-%b-%Y %H:%M:%S')
            i.SerialNumber=i.RawData[18:29].strip()
            i.ParseDateTime=datetime.datetime.now()
            i.save()






class AmrhourlydataCache(models.Model):
    using='default'
    serialnumber = models.IntegerField()
    serialport = models.IntegerField()
    logdate = models.DateTimeField(db_index=True)
    qualitycode01 = models.IntegerField(null=True, blank=True)
    hourlydata01 = models.IntegerField(null=True, blank=True)
    qualitycode02 = models.IntegerField(null=True, blank=True)
    hourlydata02 = models.IntegerField(null=True, blank=True)
    qualitycode03 = models.IntegerField(null=True, blank=True)
    hourlydata03 = models.IntegerField(null=True, blank=True)
    qualitycode04 = models.IntegerField(null=True, blank=True)
    hourlydata04 = models.IntegerField(null=True, blank=True)
    qualitycode05 = models.IntegerField(null=True, blank=True)
    hourlydata05 = models.IntegerField(null=True, blank=True)
    qualitycode06 = models.IntegerField(null=True, blank=True)
    hourlydata06 = models.IntegerField(null=True, blank=True)
    qualitycode07 = models.IntegerField(null=True, blank=True)
    hourlydata07 = models.IntegerField(null=True, blank=True)
    qualitycode08 = models.IntegerField(null=True, blank=True)
    hourlydata08 = models.IntegerField(null=True, blank=True)
    qualitycode09 = models.IntegerField(null=True, blank=True)
    hourlydata09 = models.IntegerField(null=True, blank=True)
    qualitycode10 = models.IntegerField(null=True, blank=True)
    hourlydata10 = models.IntegerField(null=True, blank=True)
    qualitycode11 = models.IntegerField(null=True, blank=True)
    hourlydata11 = models.IntegerField(null=True, blank=True)
    qualitycode12 = models.IntegerField(null=True, blank=True)
    hourlydata12 = models.IntegerField(null=True, blank=True)
    qualitycode13 = models.IntegerField(null=True, blank=True)
    hourlydata13 = models.IntegerField(null=True, blank=True)
    qualitycode14 = models.IntegerField(null=True, blank=True)
    hourlydata14 = models.IntegerField(null=True, blank=True)
    qualitycode15 = models.IntegerField(null=True, blank=True)
    hourlydata15 = models.IntegerField(null=True, blank=True)
    qualitycode16 = models.IntegerField(null=True, blank=True)
    hourlydata16 = models.IntegerField(null=True, blank=True)
    qualitycode17 = models.IntegerField(null=True, blank=True)
    hourlydata17 = models.IntegerField(null=True, blank=True)
    qualitycode18 = models.IntegerField(null=True, blank=True)
    hourlydata18 = models.IntegerField(null=True, blank=True)
    qualitycode19 = models.IntegerField(null=True, blank=True)
    hourlydata19 = models.IntegerField(null=True, blank=True)
    qualitycode20 = models.IntegerField(null=True, blank=True)
    hourlydata20 = models.IntegerField(null=True, blank=True)
    qualitycode21 = models.IntegerField(null=True, blank=True)
    hourlydata21 = models.IntegerField(null=True, blank=True)
    qualitycode22 = models.IntegerField(null=True, blank=True)
    hourlydata22 = models.IntegerField(null=True, blank=True)
    qualitycode23 = models.IntegerField(null=True, blank=True)
    hourlydata23 = models.IntegerField(null=True, blank=True)
    qualitycode24 = models.IntegerField(null=True, blank=True)
    hourlydata24 = models.IntegerField(null=True, blank=True)
    intervalchannel = models.IntegerField()
    ReverseRotationIndicator=models.NullBooleanField(db_column='reverserotationindicator', null=True, blank=True)
    Description=models.TextField(db_column='description', null=True, blank=True)
    objects=models.GeoManager()
    class Meta:
        db_table = u'amramrhourlydata'
        app_label='djangoproject'
    def __unicode__(self):
        return str(self.id)
    @staticmethod
    def RefreshCache():
        """Add all new Amrhourlydata Models from AMR, delete and recreate records that are less then 1 day old"""
        if(AmrhourlydataCache.objects.all().count()):
            StartDate=AmrhourlydataCache.objects.all().order_by('-logdate')[0].logdate - datetime.timedelta(days=1)
        else:
            StartDate=datetime.datetime.today() - datetime.timedelta(days=7)
        Days=(datetime.datetime.today() - StartDate).days + 1
        for day in range(0, Days):
            CurrentEndDate=StartDate + datetime.timedelta(days=day)
            CurrentStartDate=StartDate + datetime.timedelta(days=day) - datetime.timedelta(days=1)
            django.db.reset_queries()
            print "AmrhourlydataCache Starting Day:  " + str(CurrentStartDate) + '  At:   ' + str(datetime.datetime.now())
            AmrHourlyDataList=list(AMR.Amrhourlydata.objects.filter(logdate__gte=CurrentStartDate).filter(logdate__lte=CurrentEndDate))
            django.db.reset_queries()
            AmrhourlydataCache.objects.filter(logdate__gte=CurrentStartDate).delete()
            for i in AmrHourlyDataList:
                New=AmrhourlydataCache()
                New.serialnumber=i.serialnumber
                New.serialport=i.serialport
                New.logdate=i.logdate
                New.qualitycode01=i.qualitycode01
                New.hourlydata01=i.hourlydata01
                New.qualitycode02=i.qualitycode02
                New.hourlydata02=i.hourlydata02
                New.qualitycode03=i.qualitycode03
                New.hourlydata03=i.hourlydata03
                New.qualitycode04=i.qualitycode04
                New.hourlydata04=i.hourlydata04
                New.qualitycode05=i.qualitycode05
                New.hourlydata05=i.hourlydata05
                New.qualitycode06=i.qualitycode06
                New.hourlydata06=i.hourlydata06
                New.qualitycode07=i.qualitycode07
                New.hourlydata07=i.hourlydata07
                New.qualitycode08=i.qualitycode08
                New.hourlydata08=i.hourlydata08
                New.qualitycode09=i.qualitycode09
                New.hourlydata09=i.hourlydata09
                New.qualitycode10=i.qualitycode10
                New.hourlydata10=i.hourlydata10
                New.qualitycode11=i.qualitycode11
                New.hourlydata11=i.hourlydata11
                New.qualitycode12=i.qualitycode12
                New.hourlydata12=i.hourlydata12
                New.qualitycode13=i.qualitycode13
                New.hourlydata13=i.hourlydata13
                New.qualitycode14=i.qualitycode14
                New.hourlydata14=i.hourlydata14
                New.qualitycode15=i.qualitycode15
                New.hourlydata15=i.hourlydata15
                New.qualitycode16=i.qualitycode16
                New.hourlydata16=i.hourlydata16
                New.qualitycode17=i.qualitycode17
                New.hourlydata17=i.hourlydata17
                New.qualitycode18=i.qualitycode18
                New.hourlydata18=i.hourlydata18
                New.qualitycode19=i.qualitycode19
                New.hourlydata19=i.hourlydata19
                New.qualitycode20=i.qualitycode20
                New.hourlydata20=i.hourlydata20
                New.qualitycode21=i.qualitycode21
                New.hourlydata21=i.hourlydata21
                New.qualitycode22=i.qualitycode22
                New.hourlydata22=i.hourlydata22
                New.qualitycode23=i.qualitycode23
                New.hourlydata23=i.hourlydata23
                New.qualitycode24=i.qualitycode24
                New.hourlydata24=i.hourlydata24
                if( ((i.qualitycode01 == 3) and (i.hourlydata01 < 0)) or
                        ((i.qualitycode02 == 3) and (i.hourlydata02 < 0)) or
                        ((i.qualitycode03 == 3) and (i.hourlydata03 < 0)) or
                        ((i.qualitycode04 == 3) and (i.hourlydata04 < 0)) or
                        ((i.qualitycode05 == 3) and (i.hourlydata05 < 0)) or
                        ((i.qualitycode06 == 3) and (i.hourlydata06 < 0)) or
                        ((i.qualitycode07 == 3) and (i.hourlydata07 < 0)) or
                        ((i.qualitycode08 == 3) and (i.hourlydata08 < 0)) or
                        ((i.qualitycode09 == 3) and (i.hourlydata09 < 0)) or
                        ((i.qualitycode10 == 3) and (i.hourlydata10 < 0)) or
                        ((i.qualitycode11 == 3) and (i.hourlydata11 < 0)) or
                        ((i.qualitycode12 == 3) and (i.hourlydata12 < 0)) or
                        ((i.qualitycode13 == 3) and (i.hourlydata13 < 0)) or
                        ((i.qualitycode14 == 3) and (i.hourlydata14 < 0)) or
                        ((i.qualitycode15 == 3) and (i.hourlydata15 < 0)) or
                        ((i.qualitycode16 == 3) and (i.hourlydata16 < 0)) or
                        ((i.qualitycode17 == 3) and (i.hourlydata17 < 0)) or
                        ((i.qualitycode18 == 3) and (i.hourlydata18 < 0)) or
                        ((i.qualitycode19 == 3) and (i.hourlydata19 < 0)) or
                        ((i.qualitycode20 == 3) and (i.hourlydata20 < 0)) or
                        ((i.qualitycode21 == 3) and (i.hourlydata21 < 0)) or
                        ((i.qualitycode22 == 3) and (i.hourlydata22 < 0)) or
                        ((i.qualitycode23 == 3) and (i.hourlydata23 < 0)) or
                        ((i.qualitycode24 == 3) and (i.hourlydata24 < 0))):
                    New.ReverseRotationIndicator=True
                else:
                    New.ReverseRotationIndicator=False
                New.intervalchannel=i.intervalchannel
                New.save()
    def GetHourlyDataList(self):
        Results=[]
        GoodQualityCodes=[3]
        if(self.qualitycode01 in GoodQualityCodes):
            Results.append(self.hourlydata01)
        else:
            Results.append('N/A')
        if(self.qualitycode02 in GoodQualityCodes):
            Results.append(self.hourlydata02)
        else:
            Results.append('N/A')
        if(self.qualitycode03 in GoodQualityCodes):
            Results.append(self.hourlydata03)
        else:
            Results.append('N/A')
        if(self.qualitycode04 in GoodQualityCodes):
            Results.append(self.hourlydata04)
        else:
            Results.append('N/A')
        if(self.qualitycode05 in GoodQualityCodes):
            Results.append(self.hourlydata05)
        else:
            Results.append('N/A')
        if(self.qualitycode06 in GoodQualityCodes):
            Results.append(self.hourlydata06)
        else:
            Results.append('N/A')
        if(self.qualitycode07 in GoodQualityCodes):
            Results.append(self.hourlydata07)
        else:
            Results.append('N/A')
        if(self.qualitycode08 in GoodQualityCodes):
            Results.append(self.hourlydata08)
        else:
            Results.append('N/A')
        if(self.qualitycode09 in GoodQualityCodes):
            Results.append(self.hourlydata09)
        else:
            Results.append('N/A')
        if(self.qualitycode10 in GoodQualityCodes):
            Results.append(self.hourlydata10)
        else:
            Results.append('N/A')
        if(self.qualitycode11 in GoodQualityCodes):
            Results.append(self.hourlydata11)
        else:
            Results.append('N/A')
        if(self.qualitycode12 in GoodQualityCodes):
            Results.append(self.hourlydata12)
        else:
            Results.append('N/A')
        if(self.qualitycode13 in GoodQualityCodes):
            Results.append(self.hourlydata13)
        else:
            Results.append('N/A')
        if(self.qualitycode14 in GoodQualityCodes):
            Results.append(self.hourlydata14)
        else:
            Results.append('N/A')
        if(self.qualitycode15 in GoodQualityCodes):
            Results.append(self.hourlydata15)
        else:
            Results.append('N/A')
        if(self.qualitycode16 in GoodQualityCodes):
            Results.append(self.hourlydata16)
        else:
            Results.append('N/A')
        if(self.qualitycode17 in GoodQualityCodes):
            Results.append(self.hourlydata17)
        else:
            Results.append('N/A')
        if(self.qualitycode18 in GoodQualityCodes):
            Results.append(self.hourlydata18)
        else:
            Results.append('N/A')
        if(self.qualitycode19 in GoodQualityCodes):
            Results.append(self.hourlydata19)
        else:
            Results.append('N/A')
        if(self.qualitycode20 in GoodQualityCodes):
            Results.append(self.hourlydata20)
        else:
            Results.append('N/A')
        if(self.qualitycode21 in GoodQualityCodes):
            Results.append(self.hourlydata21)
        else:
            Results.append('N/A')
        if(self.qualitycode22 in GoodQualityCodes):
            Results.append(self.hourlydata22)
        else:
            Results.append('N/A')
        if(self.qualitycode23 in GoodQualityCodes):
            Results.append(self.hourlydata23)
        else:
            Results.append('N/A')
        if(self.qualitycode24 in GoodQualityCodes):
            Results.append(self.hourlydata24)
        else:
            Results.append('N/A')
        return Results








